<?php

/*session_set_save_handler('_open',
                         '_close',
                         '_read',
                         '_write',
                         '_destroy',
                         '_clean');*/

function _open()
{	
    global $_sess_db, $wpdb;
//trace('opening session', "...");
    if ($_sess_db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD))
    {
        return mysql_select_db(DB_NAME, $_sess_db);
    }
//trace('FAILURE-- DB_HOST, DB_USER, DB_PASSWORD', DB_HOST . DB_USER . DB_PASSWORD);
    return FALSE;
}

function _close()
{
    global $_sess_db, $wpdb;
//trace('closing session', "...");
    return mysql_close($_sess_db);
}

function _read($id)
{
    global $_sess_db, $wpdb;
//trace('reading session data for $id', "$id");
    $id = mysql_real_escape_string($id);

    $sql = "SELECT data
            FROM   $wpdb->sessions
            WHERE  id = '$id'";

    if ($result = mysql_query($sql, $_sess_db))
    {
        if (mysql_num_rows($result))
        {
            $record = mysql_fetch_assoc($result);

            return $record['data'];
        }
    }

    return '';
}

function _write($id, $data)
{   
    global $_sess_db, $wpdb;
    $access = time();

    $id = mysql_real_escape_string($id);
    $access = mysql_real_escape_string($access);
    $data = mysql_real_escape_string($data);

	//trace('writing session $id, $data', "$id, $data");
    $sql = "REPLACE 
            INTO    $wpdb->sessions
            VALUES  ('$id', '$access', '$data')";
//trace('$sql', "$sql");
    return mysql_query($sql, $_sess_db);
}

function _destroy($id)
{
    global $_sess_db, $wpdb;
trace('destroying session data for $id', "$id");    
    $id = mysql_real_escape_string($id);

    $sql = "DELETE
            FROM   $wpdb->sessions
            WHERE  id = '$id'";

    return mysql_query($sql, $_sess_db);
}

function _clean($max)
{
    global $_sess_db, $wpdb;
//trace('cleaning session data for $max', "$max");
    $old = time() - $max;
    $old = mysql_real_escape_string($old);

    $sql = "DELETE
            FROM   $wpdb->sessions
            WHERE  access < '$old'";

    return mysql_query($sql, $_sess_db);
}

?>